package com.xujianlun.cpms.controller.sys;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xujianlun.cpms.common.Response;
import com.xujianlun.cpms.mapper.sys.RoleMenuMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xujianlun.cpms.service.sys.IRoleService;
import com.xujianlun.cpms.entity.sys.Role;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xujianlun
 * @since 2022-11-24
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Resource
    private IRoleService roleService;
    @Resource
    private RoleMenuMapper roleMenuMapper;
    // 新增或者更新
    @PostMapping
    public Response save(@RequestBody Role role) {
        return Response.success(roleService.saveOrUpdate(role));
    }

    @DeleteMapping("/{id}")
    public Response delete(@PathVariable Integer id) {

        return Response.success(roleService.removeById(id));
    }

    @PostMapping("/batch")
    public Response deleteBatch(@RequestBody List<Integer> ids) {

        return Response.success(roleService.removeByIds(ids));
    }

    @GetMapping
    public Response findAll() {
        return Response.success(roleService.list());
    }

    @GetMapping("/{id}")
    public Response findOne(@PathVariable Integer id) {
        return Response.success(roleService.getById(id));
    }

    @GetMapping("/page")
    public Response findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name",name);
        queryWrapper.orderByDesc("id");
        return Response.success(roleService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    // 绑定角色和菜单的关系
    @PostMapping("/roleMenu/{roleId}")
    public Response saveRoleMenu(@PathVariable Integer roleId,@RequestBody List<Integer> menuIds) {

        roleService.setRoleMenu(roleId,menuIds);
        return Response.success();
    }
    @GetMapping("/roleMenu/{roleId}")
    public Response getRoleMenu(@PathVariable Integer roleId) {

        return Response.success(roleService.getRoleMenuByRoleId(roleId));
    }

}

